from datetime import datetime
import re
from random import randint
from flask import current_app, jsonify
from flask import make_response
from flask import request
from flask import session

from info import constants, db
from info.lib.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha.captcha import captcha
from info.utils.response_code import RET

from info.modules.passport import passport_blu
from info import redis_store


@passport_blu.route('/image_code')
def get_image_code():
    #获取路由的id
    code_id = request.args.get('code_id')
    # 获取验证码的内容信息
    name, text, image = captcha.generate_captcha()
    try:
        # 保存生成的图片验证码内容
        redis_store.setex('ImageCode_'+code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)

        return make_response(jsonify(errno=RET.DATAERR,errmsg='图片验证码保存失败'))
    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp
    # return 'post'

@passport_blu.route('/sms_code', methods=['POST'])
def send_sms():
    # 1接收参数
    param_dict = request.json
    mobile = param_dict.get('mobile')
    image_code = param_dict.get('image_code')
    image_code_id = param_dict.get('image_code_id')
    if not all ([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.DATAERR,errmsg='参数不全')
    # 2 校验手机号
    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg='手机号格式错误')
    # 2.1 校验手机号是否注册了
    count = User.query.filter_by(mobile=mobile).count()
    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg='手机号已注册')
    # 3 通过图片查询redis的图片验证码内容
    try:
        redis_code = redis_store.get("ImageCode_" + image_code_id)
        if redis_code:
            redis_code = redis_code.decode()
            redis_store.delete("ImageCode_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取图片验证码失败')
    # 3.1 判断验证码是否过期
    if not redis_code:
        return jsonify(errno=RET.DATAERR, errmsg='验证码已过期')

    # 4 验证码内容比对
    if image_code.lower() != redis_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入错误')

    # 5 生成随机短信验证码
    sms_code = '%06d'%randint(0, 999999)
    # 5.1 发给运通信使用

    result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES/60],1)
    # if result != 0:
    #
    #     return jsonify(errno=RET.DATAERR,errmsg='发送失败')
    try:
        redis_store.setex('sms_' + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='发送失败')
    return jsonify(errno=RET.OK, errmsg='ok')

#注册功能
@passport_blu.route('/register', methods=['POST'])
def register():
    # 1接收参数
    param_dict = request.json
    mobile = param_dict.get('mobile')
    smscode = param_dict.get('smscode')
    password = param_dict.get('password')
    # 1.1 检查参数是否为空
    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.DATAERR,errmsg='参数不全')

    # 2 从redis获取手机号的验证码
    try:
        redis_sms_code = redis_store.get('sms_'+mobile)
        # 2.2 删除短信验证码
        if redis_sms_code:
            redis_sms_code=redis_sms_code.decode()
            redis_store.delete('sms_'+mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='手机验证码获取失败')
    # 2.1 验证是否手机验证码过期
    if not redis_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg='手机验证码过期')
    if redis_sms_code != smscode:
        return jsonify(errno=RET.DATAERR, errmsg='验证码不一致')

    # 3 初始化user模型 并添加到数据库
    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger(e)

    # 4 保存用户登陆状态
    session['user_id']=user.id
    session['nick_name']=user.nick_name
    session['mobile']=user.mobile

    # 5 返回注册结果
    return jsonify(errno=RET.OK, errmsg='ok')


# 登录功能
@passport_blu.route('/login', methods=['POST'])
def login():
    # 1 获取参数 判断是否有值

    mobile =request.json.get('mobile')
    password =request.json.get('password')
    if not all([mobile, password]):
        return jsonify(errno=RET.DATAERR, errmsg='参数不全')

    # 2 从数据库查询指定用户
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='查询数据错误')
    if not user:
        return jsonify(errno=RET.DATAERR, errmsg='用户不存在')

    # 3 校验密码
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg='密码错误')

    # 4 保存登陆状态
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    # 4.1 记录用户最后一次登陆的时间
    user.last_login = datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    # 5 登陆成功
    return jsonify(errno=RET.OK, errmsg='ok')

# 退出功能

@passport_blu.route('/logout', methods=['POST'])
def logout():
    session.pop('user_id',None)
    session.pop('nick_name',None)
    session.pop('mobile',None)
    return jsonify(errno=RET.OK, errmsg='ok')































